<template>
    <div class="address-list">
        <!-- 标题栏 -->
        <van-nav-bar title="地址管理" left-arrow @click-left="onClickLeft">
            <template #right>
                <van-icon name="weapp-nav" size="18" />
            </template>
        </van-nav-bar>

        <!-- 列表 -->
        <!-- :disabled-list="disabledList"
            disabled-text="以下地址超出配送范围" -->
        <van-address-list v-model="chosenAddressId" :list="list"  default-tag-text="默认" @add="onAdd" @edit="onEdit" @click-item="gotoCreateOrder" />
    </div>
</template>

<script setup>
import { ref, onMounted,reactive } from "vue"
import { showToast,showConfirmDialog } from 'vant';
import { useRoute, useRouter } from "vue-router";
import { getAddressList } from '@/api/index.js'
let route = useRoute();
let router = useRouter();

let list = reactive([]); //地址列表
let chosenAddressId = ref(''); //被选中的地址id
let edit = ref(true)
// let address = reactive({
//     list: [],
//     chosenAddressId:''
// })

onMounted(() => {
    // 获取地址列表
    getAddressList().then(res => {
        let { data, resultCode } = res;
        if (resultCode == 200) {
            // map方法：创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。
           let array = data.map(item => {
                return {
                    id: item.addressId,
                    name: item.userName,
                    tel: item.userPhone,
                    address:
                        item.provinceName +
                        item.cityName +
                        item.regionName +
                        item.detailAddress,
                    isDefault:item.defaultFlag,
                }
           })
            list.push(...array)
        }
    }).then(resolve => {
        // 将list中默认地址的地址id赋值给chosenAddressId
        let res = list.filter(item=>item.isDefault==true)
        chosenAddressId.value = res[0].id
    })
})






// 新增地址事件
let onAdd = () => {
    // showToast('新增地址');
    router.push('/addressedit')
};


// 点击任意地址进入生成订单页面
let gotoCreateOrder = item => {

    if (edit.value) {
       
        showConfirmDialog({
            message: '是否选择此地址？',
            closeOnClickOverlay: true,
        }).then(() => {
            // 路由跳转并query传参
            router.replace({
                path: '/create-order',
                query: { addressId:item.id }
            })
        }).catch(() => { })
        edit.value = true
    }

}


// 编辑地址事件
let onEdit = item => {
    // onEdit事件默认参数为选中的地址的proxy
    // console.log(item.id);
    edit.value = false;
    router.push('/addressedit?addressId='+item.id)
};




// 点击顶部栏返回
let onClickLeft = () => {
    router.back()
}
</script>

<style scoped lang="less">

</style>